/* Copyright (c) 2010, Peter Lényi */
/* Licensed under The BSD License. */

package gem.apps.fs.web;

import gem.apps.fs.engine.FileServer;
import gem.apps.fs.entities.FileMeta;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet class FileDownloadPostServlet authorizes the download and sends
 * streamed file to browser.
 *
 * @author Peter Lényi
 * @version 20100509F3
 */
public class FileDownloadPostServlet extends HttpServlet
{
    private static final String ADDRESS_FATAL = "/error/fatal/jsp";
    private static final String ADDRESS_WARNING = "/file/download/jsp";
    private static final String ADDRESS_SUCCESS = "/file/details/pre";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // prepare local variables
        boolean success = false;
        List<String> messages = new ArrayList<String>();

        // prepare resources
        FileServer fs = FileServer.getInstance();
        ResourceBundle gui = ResourceBundle.getBundle("Gui");

        // load request parameters
        String uinString = request.getParameter("form.uin");
        String password = request.getParameter("form.password");
        if (password == null) {
            password = "";
        }

        // execute logic
        try {
            long uin = Long.parseLong(uinString);
            FileMeta filemeta = fs.getFileMeta(uin);
            if (filemeta.getPassword().equals(password)) {
                try {
                    FileInputStream fis = fs.loadFile(uin);
                    response.setCharacterEncoding("UTF-8");
                    response.setContentType(filemeta.getMime() + ";charset=UTF-8");
                    response.setHeader("Content-Disposition", "attachment;filename=" + filemeta.getOriginalName().replaceAll("\\ ", "_"));
                    ServletOutputStream sos = response.getOutputStream();
                    byte[] buffer = new byte[4096];
                    int amountRead = -1;
                    while ((amountRead = fis.read(buffer)) != -1) {
                        sos.write(buffer, 0, amountRead);
                    }
                    fis.close();
                    sos.close();
                    success = true;
                }
                catch (IOException ex) {
                    messages.add(gui.getString("Gui.action.file.download.err"));
                }
            }
            else {
                messages.add(gui.getString("Gui.action.authorize.no"));
            }

            // pass connection
            request.getSession().setAttribute("msg", messages);
            if (success) {
                response.sendRedirect(getServletContext().getContextPath() + ADDRESS_SUCCESS + "?uin=" + uin);
            }
            else {
                response.sendRedirect(getServletContext().getContextPath() + ADDRESS_WARNING + "?uin=" + uin);
            }
        }
        catch (NumberFormatException ex) {
            response.sendRedirect(getServletContext().getContextPath() + ADDRESS_FATAL);
        }
    }
}
